Hook과 State
✒️ 2025-05-28 10:40 내용 수정
Hook
함수 Component에서 React state와 생명주기 기능을 연동(Hook into)할 수 있게 해주는 함수
- 참고 자료 : React Hook의 개요, React Legacy Hook
- 클래스 Component가 없어도 state와 같은 특징을 사용할 수 있다.
- 공식 페이지에 따르면 16.8 버전부터 추가된 React 요소로, 기본 Component 안에서 사용할 수 있어 이전 버전들과의 호환성을 깨뜨리지 않는다.
- 최상위에서만 호출할 수 있으며, 반복문, 조건문, 중첩된 함수 내에서 실행할 수 없다.
- React 함수 Component에서만 호출할 수 있고, 일반 Javascript 함수에서는 호출할 수 없다.
State
React에서 사용하는 component에 특화된 메모리
- 참고 자료 : React dev State
- 변수를 사용했을 때 React가 Component를 렌더링할 때 지역 변수들의 변화를 고려하지 않고, 지역 변수들이 변경되었을 때 렌더를 수행하지 않아 새 데이터를 가져오기 난감하다.
- state를 사용하면 렌더 시 데이터를 가져오고, 새 데이터를 가져왔을 때 다시 렌더를 일으킬 수 있다.
- State는 격리되어(isolated)있고 private이다.
- 참고 자료 : React dev State: A Component's Memory
- State는 Component에 국한(local)되어 있어 같은 Component를 2번 렌더하더라도 각 Component는 서로 독립된 state를 가지기 때문에 하나를 바뀐다고 해서 다른 state에 영향을 끼치지 않는다.
- property와 다르게 state는 state를 선언한 Component에 완전히 private이다.
- 부모 Component가 state를 바꿀 수 없고, 한 Component에 state를 추가하거나 삭제해도 다른 Component에 영향을 주지 않는다.
useState(State Hook)
state를 함수 Component 내에서 사용할 수 있게 해주는 Hook
- 참고 자료 : React Using the State Hook
useState()Hook은 state variable과 state setter function을 제공한다.- state variable은 렌더 간의 데이터를 다시 얻어온다.
- state setter function은 state variable을 업데이트하고, React가 Component를 다시 렌더하도록 한다.
import { useState } from 'react';
const [ value, setValue ] = useState(0);
- 예제는 공식 사이트에 있는 예제를 변형했다.
import {useState} from 'react';
function Test() {
const[count, setCount] = useState(0);
const[name, setName] = useState('Tom');
const[fruits, setFruits] = useState(['banana', 'apple', 'grape', 'berry']);
return(
<>
<button onClick={()=>setCount(count + 1)}>Click Me</button>
<button onClick={()=>setName('Jerry')}>Name?</button>
<button onClick={()=>setFruits(['apple', 'kiwi'])}>Fruits</button>
</>
)
}
- state를 바꾸려면
setState함수로 관리해야 하며, state를 직접 바꾸려고 하면 에러가 발생할 수 있다. - 특히 state가
const라면 상수를 재할달 하려는 동작으로 인식되기 때문에 에러가 발생한다.
function Counter() {
const [count, setCount] = useState(0);
const increase = () => {
// count에 1을 더한 새로운 값을 할당
// count++는 상수 자체에 연산 수행
setCount(count + 1);
}
const decrease = () => {
setCount(count - 1);
}
}
export {Counter, NameList};